package com.wangzhixuan.controller;

import com.wangzhixuan.constant.SystemConstant;
import com.wangzhixuan.db.bean.Customer;
import com.wangzhixuan.db.bean.Order;
import com.wangzhixuan.db.bean.Payment;
import com.wangzhixuan.service.OrderService;
import com.wangzhixuan.util.HttpUtils;
import com.wangzhixuan.vo.JsonVo;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpPayService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.pay.WxPayOrderNotifyResponse;
import me.chanjar.weixin.mp.bean.pay.request.WxPayBaseRequest;
import me.chanjar.weixin.mp.bean.pay.request.WxPayUnifiedOrderRequest;
import me.chanjar.weixin.mp.bean.pay.result.WxPayBaseResult;
import me.chanjar.weixin.mp.bean.pay.result.WxPayOrderNotifyResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pay")
public class PayController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WxMpService wxMpService;
    @ResponseBody
    @RequestMapping(value = "wxpay")
    public JsonVo<Map> pay(HttpServletRequest request, long orderId) {
        JsonVo<Map> vo=new JsonVo<Map>();
        System.out.println("wxpay : " + orderId);
        WxMpPayService wxMpPayService = wxMpService.getPayService();
        try {
            Order order  = orderService.getOrderById(orderId);
            String basePath = HttpUtils.getBasePath(request);
            Customer currentCustomer = (Customer) request.getSession().getAttribute(SystemConstant.SESSION_CUSTOMER_KEY);
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setDeviceInfo("WEB");
            orderRequest.setBody("预付款");
            orderRequest.setOutTradeNo(orderId+"");
            orderRequest.setTotalFee(WxPayBaseRequest.yuanToFee(0.01 + ""));//元转成分
            orderRequest.setOpenid(currentCustomer.getOpenId());
            orderRequest.setSpbillCreateIp(HttpUtils.getAddr(request));
            orderRequest.setNotifyURL(basePath + "/pay/wxNotify");
            orderRequest.setTradeType("JSAPI");
            orderRequest.setTimeStart(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
            orderRequest.setTimeExpire(DateFormatUtils.format(DateUtils.addMinutes(new Date(),30), "yyyyMMddHHmmss"));


            Map<String, String> payInfo = wxMpPayService.getPayInfo(orderRequest);
            //生成jssdk api请求参数
            vo.setT(payInfo);
            vo.setResult(true);
          //  return vo;
        } catch (Exception e) {
            //log.error("微信支付失败！订单号：{},原因:{}", orderNo, e.getMessage());
            e.printStackTrace();
            vo.setResult(false);
        }
        return vo;
    }
    @ResponseBody
    @RequestMapping("/wxNotify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        WxMpPayService wxMpPayService = wxMpService.getPayService();
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxMpPayService.getOrderNotifyResult(xmlResult);
            // 结果正确
            String orderIdStr = result.getOutTradeNo();
            System.out.println("wxNotify : " + orderIdStr);
            String tradeNo = result.getTransactionId();
            String totalFee = WxPayBaseResult.feeToYuan(result.getTotalFee());
            orderIdStr=orderIdStr.replace(",","");
            long orderId=Long.parseLong(orderIdStr);
            System.out.println("orderId: "+orderId+" tradeNo: "+tradeNo+" totalFee: "+totalFee);
            Order order =orderService.getOrderById(orderId);
            if(order!=null){
                System.out.println("order status: " +order.getStatus());
            }
            if(order!=null && order.getStatus()==0){
                Payment payment=new Payment();
                payment.setOrderId(orderId);
                payment.setPayAmmount(Double.parseDouble(totalFee));
                payment.setTransaction("预付款");
                System.out.println("add payment");
                orderService.addPayment(payment);
                System.out.println("change status");
                orderService.updateOrderStatus(orderId,1);
            }else{
                System.out.println("order not fund");
            }
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            return WxPayOrderNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            //  log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayOrderNotifyResponse.fail(e.getMessage());
        }
    }
}
